package com.ittao.taoaicodemother.config;

import com.ittao.taoaicodemother.exception.BusinessException;
import com.ittao.taoaicodemother.exception.ErrorCode;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.Executor;
import java.util.concurrent.Semaphore;

/**
 * 虚拟线程执行器配置
 * 用于支持高并发异步操作，特别是项目构建和文件上传等IO密集型任务
 */
@Configuration
public class VirtualThreadExecutorConfig {

    @Resource
    private AppStorageConfig appStorageConfig;

    /**
     * 创建虚拟线程执行器
     * 使用 Thread.ofVirtual() 创建虚拟线程，适合IO密集型任务
     *
     * @return 虚拟线程执行器
     */
    @Bean("virtualThreadExecutor")
    public Executor virtualThreadExecutor() {
        return command -> Thread.ofVirtual().start(command);
    }

    /**
     * 创建项目构建专用的虚拟线程执行器
     * 使用信号量控制并发构建数量，避免资源过度消耗
     *
     * @return 项目构建虚拟线程执行器
     */
    @Bean("buildVirtualThreadExecutor")
    public Executor buildVirtualThreadExecutor() {
        int maxConcurrentBuilds = appStorageConfig.getCos().getMaxConcurrentBuilds();
        Semaphore buildSemaphore = new Semaphore(maxConcurrentBuilds);

        return command -> {
            Thread.ofVirtual().start(() -> {
                try {
                    // 获取构建许可
                    buildSemaphore.acquire();
                    try {
                        // 执行构建任务
                        command.run();
                    } finally {
                        // 释放构建许可
                        buildSemaphore.release();
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "构建任务被中断");
                }
            });
        };
    }
}